import router from '@/router';
import Api from '@/api';

function goLoginPage() {
  const currentPath = router.currentRoute.fullPath;
  !currentPath.match(/\/login/) &&
    router.replace({
      name: 'login',
      params: {
        //只能使用name才能传递params
        refererRoute: router.currentRoute,
      },
      query: {
        currentPath,
      },
    });
}

export default {
  namespaced: true,
  state: {
    userId: null,
  },
  mutations: {
    setUserId(state, payload) {
      state.userId = payload;
    },
  },
  actions: {
    doLogin({ commit, dispatch }, paylod) {
      if (!this.locked) {
        this.locked = true;
        Api.login(paylod)
          .then(res => {
            commit('setUserId', res.user_id);
            dispatch('user/getUserInfo', { root: true });
            this.locked = false;
          })
          .catch(() => {
            this.locked = false;
          });
      }
    },
    logout({ commit }) {
      if (!this.locked) {
        this.locked = true;
        Api.logout()
          .then(res => {
            commit('setUserId', 0);
            //清除用户信息
            commit(
              'user/setState',
              {
                info: null,
              },
              { root: true },
            );
            commit(
              'setState',
              {
                hasFinishedPreInfo: false,
              },
              { root: true },
            );
            goLoginPage();
            this.locked = false;
          })
          .catch(() => {
            this.locked = false;
          });
      }
    },
  },
};
